import java.util.List;

// gene of a color area
public class Gene {

	int gene[];
	int length;
	ColorArea ca;
	int num_sa;// number of sub area

	public Gene(ColorArea ca) {
		this.ca = ca;
		this.num_sa = ca.subareas.size();
		length = ca.subareas.size() * 24;
		gene = new int[length];
		this.update_gene();
		// this.show_gene();
	}

	// update the gene according to the new color of each sub area
	void update_gene() {
		gene = new int[length];
		int sa_num = 1;
		for (SubArea sa : this.ca.subareas) {
			String r = Integer.toBinaryString(sa.color.getRed());
			String g = Integer.toBinaryString(sa.color.getGreen());
			String b = Integer.toBinaryString(sa.color.getBlue());

			int index_blue = sa_num * 24 - 1;
			int index_green = index_blue - 8;
			int index_red = index_green - 8;

			int index_r = r.length() - 1;
			int index_g = g.length() - 1;
			int index_b = b.length() - 1;

			for (int i = 7; i >= 0; i--) {
				if (index_r >= 0) {
					gene[index_red] = Character.digit(r.charAt(index_r), 10);
					index_r--;
					index_red--;
				} else {
					if (index_red >= 0) {
						gene[index_red] = 0;
						index_red--;
					}

				}

				if (index_g >= 0) {
					gene[index_green] = Character.digit(g.charAt(index_g), 10);
					index_g--;
					index_green--;
				} else {
					if (index_green >= 0) {
						gene[index_green] = 0;
						index_green--;
					}
				}

				if (index_b >= 0) {
					gene[index_blue] = Character.digit(b.charAt(index_b), 10);
					index_b--;
					index_blue--;
				} else {
					if (index_blue >= 0) {
						gene[index_blue] = 0;
						index_blue--;
					}

				}
			}
			sa_num++;
		}

	}

	void show_gene() {
		int index = 0;
		System.out.println("the gene of this Color Area");
		for (int i = 0; i < this.gene.length; i++) {
			System.out.print(gene[i]);
			if ((i + 1) % 8 == 0) {
				System.out.println();
			}
			if ((i + 1) % 24 == 0) {
				System.out.println("--------- color "
						+ ca.subareas.get(index++).color);
			}
		}
	}

	static void show_gene(int[] gene) {
		System.out.println("the gene of this Array");
		for (int i = 0; i < gene.length; i++) {
			System.out.print(gene[i]);
			if ((i + 1) % 8 == 0) {
				System.out.println();
			}

		}
	}

	// get the [head, tail] part of the array
	static int[] getSubArray(int head, int tail, int[] array) {
		// if ((tail - head) != 23) {
		// System.out
		// .println("the distance between head and tail should be 23");
		// return null;
		// } else {
		int[] subArray = new int[24];
		int index = 0;
		for (int i = head; i <= tail; i++) {
			subArray[index++] = array[i];
		}
		return subArray;
		// }

	}
}
